import { ServerConfig } from './objects/ServerConfig';
import { AuthRoute } from './routes/auth';
import { MongoClient } from 'mongodb';
import { databaseUri } from './util/strutil';
import { TokenPool } from './objects/TokenPool';
import { Request, Response } from 'express';
import { WriteRoute } from './routes/write';
import { ReadRoute } from './routes/read';
const app = require('express')();
const fs = require('fs');
const bodyParser = require('body-parser');

const config = JSON.parse(fs.readFileSync('config.json')) as ServerConfig;
const mongo = new MongoClient(databaseUri(config), {
	useNewUrlParser: true,
	useUnifiedTopology: true
});
// XXX: init everything AFTER mongo is ready
mongo.connect().then(mongo => {
	setInterval(() => {
		pool.sweepToken().then(rs => {
			console.debug(`Deleted ${rs.deletedCount} expired token(s)`);
		})
	}, 30 * 60 * 1000);
}).catch(e => console.log(e));

const pool = new TokenPool(config, mongo);

app.use(bodyParser.json({
	inflate: true,
	limit: '200kb',
	strict: true
}));

app.use(bodyParser.urlencoded({
	inflate: true,
	limit: '200kb',
	extended: false
}));

const auth = new AuthRoute(app, config, mongo, pool);

const writer = new WriteRoute(mongo);
const reader = new ReadRoute(mongo);

app.get('/read', reader.read.bind(reader));

app.get('/find', reader.find.bind(reader));

app.use(pool.checkToken.bind(pool));

app.post('/write', writer.write.bind(writer));

app.use((req: Request, res: Response) => {
	res.status(404);
	res.send({
		reason: 'empty path'
	});
});

if (config.debug) {
	console.warn("You are running in DEBUG mode!");
	console.warn("Do NOT use debug mode in production!");
}

console.debug(`Listening on port ${config.port}`);
app.listen(config.port);
